package com.watermeter.android.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.watermeter.android.R;
import com.watermeter.android.adapter.UpInfoAdapter;
import com.watermeter.android.adapter.YesCBAdapter;
import com.watermeter.android.entry.UpRoute;
import com.watermeter.android.entry.curstorInfo;
import com.watermeter.android.utils.UConstants;
import com.watermeter.android.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;


/**
 * 更新客户信息
 * 
 * @author -zouqh
 * 
 */
public class UpInfoActivity extends Activity implements OnClickListener {

	private ImageView close;
	private TextView title;
    private TextView save;
    private ListView listView;
    private UpInfoAdapter adapter;
    private List<curstorInfo> upRouteList;
    public DbManager.DaoConfig daoConfig;
    ProgressDialog dialog;
    private String filePath;
    private String fileName;
    private Util util;
    private int flag=1;
    private StringBuffer stringBuffer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.yes_cb_activity);
		close = (ImageView) findViewById(R.id.close);
		title = (TextView) findViewById(R.id.title_text);
        save = (TextView) findViewById(R.id.ritgh_text);
        listView=(ListView)findViewById(R.id.listview);

		title.setText("更新信息");
        save.setText("全部上传");
        save.setVisibility(View.VISIBLE);
		close.setOnClickListener(this);
        save.setOnClickListener(this);
        selecteDate();
        stringBuffer=new StringBuffer();

        if(upRouteList!=null&&upRouteList.size()>0){
            adapter=new UpInfoAdapter(this,upRouteList);
            listView.setAdapter(adapter);
        }else{
            Toast.makeText(this,"暂无更新记录！",Toast.LENGTH_SHORT).show();
            return;
        }
        util=new Util(this);
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            flag=0;
            return;
        }
        filePath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/CBFile/";
        fileName="upinfo.txt";


	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		Intent intent ;
		switch (v.getId()) {
		case R.id.close:
			finish();
			break;
            case R.id.ritgh_text:
               if(flag!=0){
                   if (upRouteList!=null&&upRouteList.size()>0){
                       setStr();
                       System.out.println("(stringBuffer.toString()==="+stringBuffer.toString());
                       util.writeTxtToFile(stringBuffer.toString(),filePath,fileName);
                       UpsRoute();
                   }

               }else{
                   Toast.makeText(this,"请先安装SD卡！",Toast.LENGTH_SHORT).show();
               }

                break;

		default:
			break;
		}
	}

    /**
     * 获已抄表数据
     */
    private void selecteDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {
                upRouteList= manager.selector(curstorInfo.class).findAll();

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    //上传抄表路线
    public void UpsRoute() {
        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        RequestParams params = new RequestParams(UConstants.UPDATE_URL);
        params.addBodyParameter("CBY", UConstants.EmpId);
        params.addBodyParameter("file", new File(filePath+fileName));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Toast.makeText(x.app(), "上传成功！", Toast.LENGTH_LONG).show();
                          upRouteList.clear();
                          adapter.notifyDataSetChanged();
                            deleteDate();
                        } else {
                            Toast.makeText(x.app(), "上传失败！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "上传出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 删除已抄表数据
     */
    private void deleteDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {
            manager.delete(curstorInfo.class);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    private void setStr(){
        for (int i=0;i<upRouteList.size();i++){
            curstorInfo info=upRouteList.get(i);
//            stringBuffer.append(info.getUSERID())
//           .append("|01|").
//           append(info.getUSERNAME()).append("\r\n").append(info.getUSERID())
//                    .append("|02|").
//                    append(info.getLXDH()).append("\r\n").append(info.getUSERID())
//                    .append("|03|").
//                    append(info.getSBBH()).append("\r\n").append(info.getUSERID())
//                    .append("|04|").
//                    append(info.getXXDZ()).append("\r\n").append(info.getUSERID())
//                    .append("|05|").
//                    append(info.getCBXH()).append("\r\n").append(info.getUSERID())
//                    .append("|06|").
//                    append(info.getSBZT()).append("\r\n").append(info.getUSERID())
//                    .append("|11|").
//                    append(info.getBZXX()).append("\r\n");

            if (!info.getNUSERNAME().equals("null")){
                stringBuffer.append(info.getUSERID())
                        .append("|01|").
                        append(info.getUSERNAME()).append("\r\n");
            }
            if (!info.getNLXDH().equals("null")){
                stringBuffer.append(info.getUSERID())
                        .append("|02|").
                        append(info.getLXDH()).append("\r\n");
            }

            if (!info.getNSBBH().equals("null")){
                stringBuffer.append(info.getUSERID())
                        .append("|03|").
                        append(info.getSBBH()).append("\r\n");
            }

            if (!info.getNXXDZ().equals("null")){
                stringBuffer.append(info.getUSERID())
                        .append("|04|").
                        append(info.getXXDZ()).append("\r\n");
            }

            if (!info.getNCBXH().equals("null")){
                stringBuffer.append(info.getUSERID())
                        .append("|05|").
                        append(info.getCBXH()).append("\r\n");
            }

            if (!info.getNSBZT().equals("null")){
                stringBuffer.append(info.getUSERID())
                        .append("|06|").
                        append(info.getSBZT()).append("\r\n");
            }


            if (!info.getNBZXX().equals("null")){

                stringBuffer.append(info.getUSERID())
                        .append("|11|").
                        append(info.getBZXX()).append("\r\n");
            }

        }
        Log.i("写文件------",stringBuffer.toString());
    }

}
